-- Leviathan (c) v.v.balashoff
local Class = require('leviathan/Class')

local TextureComponent = Class:derive('TextureComponent')

function TextureComponent:new(texture, x, y, w, h, halign, valign, keepAspect, alpha)
    self.id = 'TextureComponent'
    self.typeId = 'Renderable'
    self.drawable = true
    self.enabled = true

    local orgPicW = texture:getWidth()
    local orgPicH = texture:getHeight()

    self.x = x or 0
    self.y = y or 0
    self.w = w or orgPicW
    self.h = h or orgPicH
    self.scaleX = 1
    self.scaleY = 1
    self.halign = halign or 'center'
    self.valign = valign or 'center'
    self.keepAspect = keepAspect or false
    self.alpha = alpha or 1
    -- rounding values
    self.x = math.floor(self.x)
    self.y = math.floor(self.y)
    self.w = math.floor(self.w)
    self.h = math.floor(self.h)

    -- calculating scales
    if not (self.w == orgPicW) then
        self.scaleX = self.w / orgPicW
    end

    if not (self.h == orgPicH) then
        self.scaleY = self.h / orgPicH
    end
    -- keeping aspect if needed
    if keepAspect then
        if self.scaleX > self.scaleY then
            self.scaleX = self.scaleY
        else
            self.scaleY = self.scaleX
        end
    end
    -- halign correction
    if self.halign == 'right' then
        self.x = self.w - orgPicW * self.scaleX
    end
    if self.halign == 'center' then
        self.x = (self.w - orgPicW * self.scaleX) / 2
    end
    -- valign correction
    if self.valign == 'bottom' then
        self.y = self.h - orgPicH * self.scaleY
    end
    if self.valign == 'center' then
        self.y = (self.h - orgPicH * self.scaleY) / 2
    end

    -- creating new buffer and store texture in it
    self.buffer = love.graphics.newCanvas(self.w, self.h)
    love.graphics.setCanvas(self.buffer)
    love.graphics.draw(texture, self.x, self.y, 0, self.scaleX, self.scaleY)
    -- restore default canvas
    love.graphics.setCanvas()
    -- restore default color
    love.graphics.setColor(1, 1, 1, 1)

    -- reset coordinates and scale because we created buffer with needed texture
    self.x = x or 0
    self.y = y or 0
    self.scale = 1
end

return TextureComponent
